package com.icesoft.base.manager.config.resolver;

import com.icesoft.base.manager.base.BaseUser;
import com.icesoft.core.common.helper.AnnotationUtil;
import com.icesoft.core.web.suppose.token.AuthTokenCheck;
import com.icesoft.core.web.suppose.token.AuthTokenHolder;
import com.icesoft.core.web.suppose.token.IAuthToken;
import lombok.AllArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 通过authToken获取当前接口用户参数解析器
 *
 * @author XHH
 * @date 2021/1/28 17:30
 */
@AllArgsConstructor
public class AuthTokenUserArgumentResolver implements HandlerMethodArgumentResolver {
    private final ITokenUserService tokenUserService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (!BaseUser.class.isAssignableFrom(parameter.getParameterType())
                || IAuthToken.class.isAssignableFrom(parameter.getParameterType())) {
            return false;
        }
        AuthTokenCheck authTokenCheck = AnnotationUtil.findAnyAnnotation(parameter.getMethod(), AuthTokenCheck.class);
        return authTokenCheck != null && !authTokenCheck.disable();
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        if (tokenUserService == null) {
            throw new ServletRequestBindingException("tokenUserService must not be null, please implement interface: ITokenUserService");
        }
        return tokenUserService.loadUserByAuthToken(AuthTokenHolder.getAuthToken(Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class))));
    }
}
